package com.stu.utils;

import java.io.IOException;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.util.ValueStack;
import com.stu.entity.permission.User;
/**
 * 
 * @author lijian
 *
 */
public class CommonUtils implements LoggerUtils{
	/**
	 * 获得request
	 * 
	 * @return
	 */
	public static HttpServletRequest getRequest() {
		return ServletActionContext.getRequest();
	}

	/**
	 * 获得response
	 * 
	 * @return
	 */
	public static HttpServletResponse getResponse() {
		return ServletActionContext.getResponse();
	}
	

	/**
	 * session中存放数据
	 * 
	 * @param sessionAttrName
	 *            变量的名字
	 * @param obj
	 */
	public static void setSessionAttribute(String sessionAttrName, Object obj) {
		ServletActionContext.getRequest().getSession().setAttribute(sessionAttrName, obj);
	}

	/**
	 * 获取session中的数据
	 * 
	 * @param sessionAttrName
	 *            变量的名字
	 * @return 变量值
	 */
	public static Object getSessionAttribute(String sessionAttrName) {
		return ServletActionContext.getRequest().getSession().getAttribute(sessionAttrName);
	}

	/**
	 * 
	 * 移除session中的数据
	 * 
	 * @param sessionAttrName
	 *            变量的名字
	 */
	public static void removeSessionAttribute(String sessionAttrName) {
		ServletActionContext.getRequest().getSession().removeAttribute(sessionAttrName);
	}

	/**
	 * 注销session
	 */
	public static void removeSession() {
		ServletActionContext.getRequest().getSession().invalidate();
	}
	/**
	 * 获取值栈
	 * @return
	 */
	public static ValueStack getValueStack(){
		//return (ValueStack)getRequest().getAttribute("struts.valueStack");
		return ActionContext.getContext().getValueStack();
	}
	
	/**
	 * 获得请求路径
	 * 
	 * @param request
	 * @return
	 */
	public static String getRequestPath(HttpServletRequest request) {
		String requestPath = request.getRequestURI();
		requestPath = requestPath.substring(request.getContextPath().length() + 1);// 去掉项目路径
		return requestPath;
	}
	
	/**
	 * 获取当前后台用户信息
	 * @author lijian
	 *
	 * @param attributeName 属性名 默认 currentUser
	 * @return
	 */
	public static User getCurrentUser(String attributeName){
		if("".equals(attributeName)||null==attributeName){
			attributeName="currentUser";
		}
		return (User) getSessionAttribute(attributeName);
	}
	
	/**
	 * 将 json 写回 前台
	 * @author lijian
	 * @param json json 串
	 * @throws IOException
	 */
	public static void writeJson(Object json) throws IOException{
		getResponse().setContentType("text/html;charset=utf-8");
		getResponse().getWriter().write(json+"");
		getResponse().getWriter().flush();
		getResponse().getWriter().close();
	}
	
	public static String createUUID(){
		return UUID.randomUUID().toString().replaceAll("-", "").toLowerCase();
	}
}
